package com.sds.sweng.swat.miplatform.ui.design.policies;

import java.util.List;

import org.eclipse.gef.editpolicies.NonResizableEditPolicy;

import com.sds.sweng.swat.miplatform.ui.design.figures.geps.GepsTab;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TabContentsSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TabHeaderSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.component.MTab;
import com.sds.sweng.swat.miplatform.ui.design.parts.MiplatformDesignPart;
import com.sds.sweng.swat.miplatform.ui.design.parts.area.sub.TabContentsSubAreaPart;
import com.sds.sweng.swat.miplatform.ui.design.parts.component.MTabPart;

public class TabSelectionEditPolicy extends NonResizableEditPolicy {

	protected List createSelectionHandles() {
		try {
			MTab selectedTab = (MTab) getHost().getModel();
			MTabPart selectedTabPart = (MTabPart) getHost();

			TabContentsSubAreaPart tabContentsSubAreaPart =
				(TabContentsSubAreaPart) getHost().getParent().getParent().getParent().getChildren().get(1);
			TabContentsSubArea tabContentsSubArea = (TabContentsSubArea) tabContentsSubAreaPart.getModel();

			TabHeaderSubArea subArea = (TabHeaderSubArea) getHost().getParent().getModel();
			List tabs = subArea.getChildren();
			List tabParts = getHost().getParent().getChildren();

			for (int i=0;i<tabs.size();i++) {
				MTab tab = (MTab) tabs.get(i);
				MTabPart tabPart = (MTabPart) tabParts.get(i);
				if (!selectedTab.equals(tab) && tab.isSelected()) {
					tab.setSelected(false);
					tab.refresh();
					((GepsTab) tabPart.getFigure()).setSelected(false);
				}
			}

			if (!selectedTab.isSelected()) {
				selectedTab.setSelected(true);
				selectedTab.refresh();
				((GepsTab) selectedTabPart.getFigure()).setSelected(true);
			}

			tabContentsSubArea.setContents(selectedTab.getTabContents());
			((MiplatformDesignPart) tabContentsSubAreaPart.getChildren().get(0)).resizeFigure();
		} catch (Exception e) {
			// Ignore
		}

		return super.createSelectionHandles();
	}

}
